<!--  -->
<template>
  <div class="login-account">
    <el-form label-width="60px" :rules="rules" :model="account" ref="formRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue'
import { rules } from '../config/account-config' //导入校验规则
import LocalCache from '../../../ultills/cache'
import { useStore } from 'vuex'
export default defineComponent({
  setup() {
    const store = useStore()
    const account = reactive({
      name: LocalCache.getCache('name') ?? 'coderwhy', //从储存中拿到我们的内容
      password: LocalCache.getCache('password') ?? '123456'
    })
    const formRef = ref() //绑定表单组件
    const loginAction = (isKeepPassWord) => {
      // 接受传递过来的参数
      //验证 拿到表单组件formRef.value
      formRef.value.validate((valid) => {
        //拿到表单组件之后执行validate回调，传入一个参数，如果表单验证成功则valid的值为true否则为false
        if (valid) {
          // 表单验证通过执行登录逻辑
          // 判断是否要记住密码
          if (isKeepPassWord) {
            // 通过localstorage缓存密码
            LocalCache.setCache('name', account.name)
            LocalCache.setCache('password', account.password)
          } else {
            // 用户没有选择记住密码需要将存储中的密码清空
            LocalCache.deleceCache('name')
            LocalCache.deleceCache('password')
          }
          // 开始登陆验证
          // 发送提交，找到login模块，提交accountLoginAction事件，并将account结构出来的值传过去
          store.dispatch('login/accountLoginAction', { ...account })
        }
      })
    }
    return {
      account,
      rules,
      loginAction,
      formRef
    }
  }
})
</script>
<style lang="less" scoped></style>
